import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import '../../theme/theme.dart';

/// Miaoyi 输入框组件
///
/// 输入框组件，支持多种样式和状态
/// 包括基础输入框、带图标输入框、带标签输入框、禁用状态等
class HInput extends StatefulWidget {
  /// 创建一个输入框组件
  /// 输入框的初始值
  final String? value;

  /// 提示文本
  final String? hintText;

  /// 标签文本
  final String? labelText;

  /// 前缀图标
  final Widget? prefixIcon;

  /// 后缀图标
  final Widget? suffixIcon;

  /// 是否隐藏输入内容，用于密码输入
  final bool obscureText;

  /// 是否启用
  final bool enabled;

  /// 是否只读
  final bool readOnly;

  /// 最大行数
  final int maxLines;

  /// 最小行数
  final int? minLines;

  /// 最大输入长度
  final int? maxLength;

  /// 键盘类型
  final TextInputType? keyboardType;

  /// 键盘动作按钮类型
  final TextInputAction? textInputAction;

  /// 内容变化回调
  final ValueChanged<String>? onChanged;

  /// 提交回调
  final ValueChanged<String>? onSubmitted;

  /// 验证函数
  final FormFieldValidator<String>? validator;

  /// 错误文本
  final String? errorText;

  /// 边框类型
  final HInputBorderType borderType;

  /// 输入框大小
  final HInputSize size;

  /// 文本控制器
  final TextEditingController? controller;

  /// 焦点节点
  final FocusNode? focusNode;

  /// 文本对齐方式
  final TextAlign textAlign;

  /// 是否自动获取焦点
  final bool autofocus;

  /// 是否自动更正
  final bool autocorrect;

  /// 是否启用输入建议
  final bool enableSuggestions;

  /// 文本样式
  final TextStyle? style;


  ///
  /// [value] 输入框的初始值
  /// [hintText] 提示文本
  /// [labelText] 标签文本
  /// [prefixIcon] 前缀图标
  /// [suffixIcon] 后缀图标
  /// [obscureText] 是否隐藏输入内容，用于密码输入
  /// [enabled] 是否启用
  /// [readOnly] 是否只读
  /// [maxLines] 最大行数，默认为1
  /// [minLines] 最小行数
  /// [maxLength] 最大输入长度
  /// [keyboardType] 键盘类型
  /// [textInputAction] 键盘动作按钮类型
  /// [onChanged] 内容变化回调
  /// [onSubmitted] 提交回调
  /// [validator] 验证函数
  /// [errorText] 错误文本
  /// [borderType] 边框类型
  /// [size] 输入框大小
  /// 
  const HInput({
    super.key,
    this.value,
    this.hintText,
    this.labelText,
    this.prefixIcon,
    this.suffixIcon,
    this.obscureText = false,
    this.enabled = true,
    this.readOnly = false,
    this.maxLines = 1,
    this.minLines,
    this.maxLength,
    this.keyboardType,
    this.textInputAction,
    this.onChanged,
    this.onSubmitted,
    this.validator,
    this.errorText,
    this.borderType = HInputBorderType.outline,
    this.size = HInputSize.normal,
    this.controller,
    this.focusNode,
    this.textAlign = TextAlign.start,
    this.autofocus = false,
    this.autocorrect = true,
    this.enableSuggestions = true,
    this.style,
  });


  @override
  State<HInput> createState() => _HInputState();
}

class _HInputState extends State<HInput> {
  late TextEditingController _controller;
  late FocusNode _focusNode;
  bool _hasFocus = false;
  String? _errorText;

  @override
  void initState() {
    super.initState();
    _controller = widget.controller ?? TextEditingController(text: widget.value);
    _focusNode = widget.focusNode ?? FocusNode();
    _focusNode.addListener(_handleFocusChange);
    _errorText = widget.errorText;
  }

  @override
  void didUpdateWidget(HInput oldWidget) {
    super.didUpdateWidget(oldWidget);
    if (widget.controller != oldWidget.controller) {
      if (oldWidget.controller == null) {
        _controller.dispose();
      }
      _controller = widget.controller ?? TextEditingController(text: widget.value);
    }
    
    if (widget.focusNode != oldWidget.focusNode) {
      if (oldWidget.focusNode == null) {
        _focusNode.removeListener(_handleFocusChange);
        _focusNode.dispose();
      }
      _focusNode = widget.focusNode ?? FocusNode();
      _focusNode.addListener(_handleFocusChange);
    }

    if (widget.errorText != oldWidget.errorText) {
      _errorText = widget.errorText;
    }
  }

  @override
  void dispose() {
    if (widget.controller == null) {
      _controller.dispose();
    }
    if (widget.focusNode == null) {
      _focusNode.removeListener(_handleFocusChange);
      _focusNode.dispose();
    }
    super.dispose();
  }

  void _handleFocusChange() {
    if (_focusNode.hasFocus != _hasFocus) {
      setState(() {
        _hasFocus = _focusNode.hasFocus;
      });
    }
  }

  InputDecoration _getInputDecoration() {
    final theme = HTheme.of(context);
    final colors = theme.colors;
    final dimens = theme.dimens;
    
    // 根据尺寸确定内边距
    EdgeInsetsGeometry contentPadding;
    switch (widget.size) {
      case HInputSize.large:
        contentPadding = EdgeInsets.symmetric(
          vertical: dimens.inputPaddingLargeV,
          horizontal: dimens.inputPaddingLargeH,
        );
        break;
      case HInputSize.small:
        contentPadding = EdgeInsets.symmetric(
          vertical: dimens.inputPaddingSmallV,
          horizontal: dimens.inputPaddingSmallH,
        );
        break;
      case HInputSize.mini:
        contentPadding = EdgeInsets.symmetric(
          vertical: dimens.inputPaddingMiniV,
          horizontal: dimens.inputPaddingMiniH,
        );
        break;
      case HInputSize.normal:
      contentPadding = EdgeInsets.symmetric(
          vertical: dimens.inputPaddingV,
          horizontal: dimens.inputPaddingH,
        );
        break;
    }

    // 根据边框类型创建边框
    InputBorder enabledBorder;
    InputBorder focusedBorder;
    InputBorder errorBorder;
    InputBorder focusedErrorBorder;
    InputBorder disabledBorder;

    final borderRadius = BorderRadius.circular(dimens.inputBorderRadius);
    final borderWidth = dimens.inputBorderWidth;
    final focusedBorderWidth = dimens.inputFocusedBorderWidth;

    switch (widget.borderType) {
      case HInputBorderType.underline:
        enabledBorder = UnderlineInputBorder(
          borderSide: BorderSide(
            color: colors.inputBorderColor,
            width: borderWidth,
          ),
        );
        focusedBorder = UnderlineInputBorder(
          borderSide: BorderSide(
            color: colors.primary,
            width: focusedBorderWidth,
          ),
        );
        errorBorder = UnderlineInputBorder(
          borderSide: BorderSide(
            color: colors.danger,
            width: borderWidth,
          ),
        );
        focusedErrorBorder = UnderlineInputBorder(
          borderSide: BorderSide(
            color: colors.danger,
            width: focusedBorderWidth,
          ),
        );
        disabledBorder = UnderlineInputBorder(
          borderSide: BorderSide(
            color: colors.inputDisabledBorderColor,
            width: borderWidth,
          ),
        );
        break;
      case HInputBorderType.none:
        enabledBorder = InputBorder.none;
        focusedBorder = InputBorder.none;
        errorBorder = InputBorder.none;
        focusedErrorBorder = InputBorder.none;
        disabledBorder = InputBorder.none;
        break;
      case HInputBorderType.outline:
      default:
        enabledBorder = OutlineInputBorder(
          borderRadius: borderRadius,
          borderSide: BorderSide(
            color: colors.inputBorderColor,
            width: borderWidth,
          ),
        );
        focusedBorder = OutlineInputBorder(
          borderRadius: borderRadius,
          borderSide: BorderSide(
            color: colors.primary,
            width: focusedBorderWidth,
          ),
        );
        errorBorder = OutlineInputBorder(
          borderRadius: borderRadius,
          borderSide: BorderSide(
            color: colors.danger,
            width: borderWidth,
          ),
        );
        focusedErrorBorder = OutlineInputBorder(
          borderRadius: borderRadius,
          borderSide: BorderSide(
            color: colors.danger,
            width: focusedBorderWidth,
          ),
        );
        disabledBorder = OutlineInputBorder(
          borderRadius: borderRadius,
          borderSide: BorderSide(
            color: colors.inputDisabledBorderColor,
            width: borderWidth,
          ),
        );
        break;
    }

    return InputDecoration(
      contentPadding: contentPadding,
      hintText: widget.hintText,
      labelText: widget.labelText,
      prefixIcon: widget.prefixIcon,
      suffixIcon: widget.suffixIcon,
      errorText: _errorText,
      filled: true,
      fillColor: widget.enabled 
          ? colors.inputFillColor 
          : colors.inputDisabledFillColor,
      hintStyle: theme.textStyles.inputHint,
      labelStyle: theme.textStyles.inputLabel,
      errorStyle: theme.textStyles.inputError,
      enabledBorder: enabledBorder,
      focusedBorder: focusedBorder,
      errorBorder: errorBorder,
      focusedErrorBorder: focusedErrorBorder,
      disabledBorder: disabledBorder,
      isDense: widget.size == HInputSize.mini || widget.size == HInputSize.small,
    );
  }

  @override
  Widget build(BuildContext context) {
    final theme = HTheme.of(context);
    
    // 根据尺寸确定文本样式
    TextStyle textStyle;
    switch (widget.size) {
      case HInputSize.large:
        textStyle = theme.textStyles.inputLarge;
        break;
      case HInputSize.small:
        textStyle = theme.textStyles.inputSmall;
        break;
      case HInputSize.mini:
        textStyle = theme.textStyles.inputMini;
        break;
      case HInputSize.normal:
      default:
        textStyle = theme.textStyles.input;
        break;
    }

    // 合并自定义样式
    final effectiveTextStyle = widget.style != null 
        ? textStyle.merge(widget.style) 
        : textStyle;
    
    // 禁用状态的样式
    final finalTextStyle = widget.enabled 
        ? effectiveTextStyle 
        : effectiveTextStyle.copyWith(
            color: theme.colors.inputDisabledTextColor,
          );

    return TextField(
      controller: _controller,
      focusNode: _focusNode,
      decoration: _getInputDecoration(),
      style: finalTextStyle,
      obscureText: widget.obscureText,
      enabled: widget.enabled,
      readOnly: widget.readOnly,
      maxLines: widget.maxLines,
      minLines: widget.minLines,
      maxLength: widget.maxLength,
      keyboardType: widget.keyboardType,
      textInputAction: widget.textInputAction,
      textAlign: widget.textAlign,
      autofocus: widget.autofocus,
      autocorrect: widget.autocorrect,
      enableSuggestions: widget.enableSuggestions,
      onChanged: (value) {
        if (widget.validator != null) {
          final error = widget.validator!(value);
          if (error != _errorText) {
            setState(() {
              _errorText = error;
            });
          }
        }
        if (widget.onChanged != null) {
          widget.onChanged!(value);
        }
      },
      onSubmitted: widget.onSubmitted,
    );
  }
}

/// 输入框边框类型
enum HInputBorderType {
  /// 轮廓边框
  outline,
  
  /// 下划线边框
  underline,
  
  /// 无边框
  none,
}

/// 输入框尺寸
enum HInputSize {
  /// 大号
  large,
  
  /// 正常
  normal,
  
  /// 小号
  small,
  
  /// 迷你
  mini,
}

/// 带表单验证功能的输入框
class HFormInput extends FormField<String> {
  /// 创建一个带表单验证功能的输入框
  HFormInput({
    Key? key,
    String? initialValue,
    String? hintText,
    String? labelText,
    Widget? prefixIcon,
    Widget? suffixIcon,
    bool obscureText = false,
    bool enabled = true,
    bool readOnly = false,
    int maxLines = 1,
    int? minLines,
    int? maxLength,
    TextInputType? keyboardType,
    TextInputAction? textInputAction,
    ValueChanged<String>? onChanged,
    ValueChanged<String>? onSubmitted,
    FormFieldValidator<String>? validator,
    String? errorText,
    HInputBorderType borderType = HInputBorderType.outline,
    HInputSize size = HInputSize.normal,
    TextEditingController? controller,
    FocusNode? focusNode,
    TextAlign textAlign = TextAlign.start,
    bool autofocus = false,
    bool autocorrect = true,
    bool enableSuggestions = true,
    TextStyle? style,
    AutovalidateMode autovalidateMode = AutovalidateMode.disabled,
    FormFieldSetter<String>? onSaved,
  }) : super(
    key: key,
    initialValue: initialValue,
    validator: validator,
    autovalidateMode: autovalidateMode,
    onSaved: onSaved,
    builder: (FormFieldState<String> field) {
      final _HFormInputState state = field as _HFormInputState;
      return HInput(
        value: state.value,
        hintText: hintText,
        labelText: labelText,
        prefixIcon: prefixIcon,
        suffixIcon: suffixIcon,
        obscureText: obscureText,
        enabled: enabled,
        readOnly: readOnly,
        maxLines: maxLines,
        minLines: minLines,
        maxLength: maxLength,
        keyboardType: keyboardType,
        textInputAction: textInputAction,
        onChanged: (value) {
          field.didChange(value);
          if (onChanged != null) {
            onChanged(value);
          }
        },
        onSubmitted: onSubmitted,
        errorText: field.errorText,
        borderType: borderType,
        size: size,
        controller: state._controller,
        focusNode: focusNode,
        textAlign: textAlign,
        autofocus: autofocus,
        autocorrect: autocorrect,
        enableSuggestions: enableSuggestions,
        style: style,
      );
    },
  );

  @override
  FormFieldState<String> createState() => _HFormInputState();
}

class _HFormInputState extends FormFieldState<String> {
  TextEditingController? _controller;

  @override
  void initState() {
    super.initState();
    _controller = TextEditingController(text: widget.initialValue);
  }

  @override
  void dispose() {
    _controller?.dispose();
    super.dispose();
  }

  @override
  HFormInput get widget => super.widget as HFormInput;
} 